
/**
 * 
 * @class ObserverSubject Observer.hpp
 *
 * The Observer Pattern
 *
 * $Id: Observer.cpp 2 2012-05-22 17:55:16Z gerry@gaboury.biz $
 */


#include "Observer.hpp"

//Observer::Observer() : m_subject(0) { }

Observer::Observer ( ObserverSubject* p_subject ) :
  m_subject(p_subject)
{ }

Observer::~Observer ()
{
  if ( m_subject )
    m_subject->detach(this);
}

void
Observer::detach()
{
  m_subject = 0;
}

// void
// Observer::subject ( ObserverSubject* p_subject )
// {
//   if ( ! m_subject )  // set subject
//     m_subject = p_subject;
//   else if ( ! p_subject ) // unset subject
//     m_subject = 0;
// }

ObserverSubject::~ObserverSubject()
{ }

void
ObserverSubject::attach ( Observer* p_observer )
{
  // the return value could be checked
  m_observers.insert ( p_observer );
  // set subject
  //p_observer->subject ( this );
}

void
ObserverSubject::detach ( Observer*  p_observer )
{
  ObserverSetIter iter;
  if ( ( iter = m_observers.find ( p_observer ) ) != m_observers.end() )
    {
      m_observers.erase ( iter );
    }
  // unset subject
  //p_observer->subject(0);
}

void
ObserverSubject::notify ()
{
  ObserverSetIter iter;
  for ( iter = m_observers.begin(); iter != m_observers.end(); ++iter )
    {
      (*iter)->update ();
    }
}
